﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace PMCSerialTransfer.Packets
{
    class ReqSendPacket: APacket
    {
         public override bool Packet(byte[] Data)
        {
            return Process(Data);
        }

         public override bool EndProcess(bool Ok)
         {
             if (Ok)
             {
                 Globals.FileStream.Write(Globals.DataPacket, 0, Globals.DataPacket.Length);
                 Globals.FilePtr += Globals.DataPacket.Length;
                 if (Globals.FilePtr>= Globals.FileLen)
                 {
                     Globals.Message = ".\nFile Received\n";
                     Globals.FileStream.Close();
                     Globals.ProgressEvent = Globals.ProgressType.Clear;
                     Globals.DataPacket = new byte[1];
                     Globals.DataPacket[0] = (byte)Globals.ACKType.E_ACK;
                 }
                 else
                 {
                     Globals.Message = ".";
                     Globals.ProgressEvent = Globals.ProgressType.Add;
                     Globals.PacketSize = Globals.DataPacket.Length;

                     Globals.DataPacket = new byte[1];
                     Globals.DataPacket[0] = (byte)Globals.ACKType.E_ACK;

                 }
             }
             else
             {
                 Globals.ErrorCount++;
                 if (Globals.ErrorCount < 10)
                 {
                     Globals.Message = "CRC Error.. Retrying\n";
                     Globals.DataPacket[0] = (byte)Globals.ACKType.E_ERR;
                 }
                 else
                 {
                     Globals.Message = "Transfer Error.. Aborting\n";
                     Globals.DataPacket[0] = (byte)Globals.ACKType.E_ABORT;
                     Globals.FileStream.Close();
                     File.Delete(Globals.FileStream.Name);
                 }
             }
             Globals.Create((byte)CommFactory.Command.SndACK, Globals.DataPacket);
             return Ok;
         }
    }
}
